package com.itheima.protocol.disruptor;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lmax.disruptor.WorkHandler;

public class UtranUuEventDisruptorHandler implements WorkHandler<UtranUuDisruptorEvent> {
    
    private static final Logger logger = LoggerFactory.getLogger(UtranUuEventDisruptorHandler.class);
    public final static long TIME2CLEANMAP_15S = 15 * 1000;

    @SuppressWarnings("unchecked")
    @Override
    public void onEvent(UtranUuDisruptorEvent uuExtendDisruptorEvent) throws Exception {

        final String ckearMapKey = uuExtendDisruptorEvent.getCkearMapKey();
        final Map<String, Object> clearMap = (Map<String, Object>) uuExtendDisruptorEvent.getJobRunRemoveMap();
        long recordMapKeyTime = uuExtendDisruptorEvent.getClearTime();
        long clearMaptime = System.currentTimeMillis() - recordMapKeyTime;

        if (clearMaptime == TIME2CLEANMAP_15S) {
            this.UuExtendEventDisruptorClearMap(clearMap, ckearMapKey);
            
        } else if (TIME2CLEANMAP_15S - clearMaptime < 0) {
            this.UuExtendEventDisruptorClearMap(clearMap, ckearMapKey);

        } else {
            TimeUnit.MILLISECONDS.sleep(TIME2CLEANMAP_15S - clearMaptime);
            this.UuExtendEventDisruptorClearMap(clearMap, ckearMapKey);
        }
    }

    public void UuExtendEventDisruptorClearMap(Map<String, Object> clearMap, String ckearMapKey) {
        try {
            if (!clearMap.isEmpty()) {
                Set<String> jobRunRemoveMapKeySet = clearMap.keySet();
                if (jobRunRemoveMapKeySet.contains(ckearMapKey)) {
                    clearMap.remove(ckearMapKey);
                    logger.info("The key(" + ckearMapKey + ") in the map has been cleaned.");
                }
            }
            logger.debug("Maps clean up the succeed...");
        } catch (Exception e) {
            logger.debug("Maps clean up the failure...");
        }
    }
}